package commands;

import user.User;
import messages.MatchStartedMessage;
import messages.InvalidInvitationReplyMessage;
import messages.InvitationReplyMessage;
import messages.Message;
import core.GameManager;
import core.Invitation;
import event.MatchStartedEventArgs;
import event.InvalidInvitationReplyEventArgs;
import event.InvitationReplyEventArgs;
import game.Match;
import game.Player;

/**
 * The InviteReply command.
 * 
 * This command will handle replys of invite messages.
 */
public class InvitationReplyCommand extends Command {

	
	public InvitationReplyCommand(Message message, User user) {
		super(message, user);
	}
	
	
	@Override
	public void execute() {		
		GameManager gameManager = this.controller.getGameManager();
		InvitationReplyMessage message = (InvitationReplyMessage) this.message;
		Player replySender = this.user.getPlayer();
		
		
		// Must synchronize the game manager!
		synchronized(gameManager) {
		
			if (!gameManager.containsInvitation(message.getReplyId())) {	
				
				// The invitation is not valid. Lets send an InvalidInvitationReplyMessage 
				// to notify the client.
				
				InvalidInvitationReplyEventArgs args = new InvalidInvitationReplyEventArgs(
						new InvalidInvitationReplyMessage(message.getReplyId()), replySender);
				this.controller.fireInvalidInvitationReplyEvent(args);
			} else {
				Invitation invitation = gameManager.getInvitation(message.getReplyId());
				InvitationReplyEventArgs args = new InvitationReplyEventArgs(invitation, message);	
				
				this.controller.fireInvitationReplyEvent(args);
				
				// Invitation was sent. Players are notified. The invitation is no 
				// longer pending.
				gameManager.removeInvitation(message.getReplyId());
				
				// If the player accepted the invitation, let the games begin!
				if (message.isAccepted()) {					
					Match match = gameManager.getGameByName(invitation.getGameName()).createMatch();
					match.addPlayer(invitation.getSender());
					match.addPlayer(invitation.getDestiny());
					match.start();
					
					gameManager.addMatch(match);
					
					MatchStartedMessage gameMessage = new MatchStartedMessage(invitation.getId(),
							match.getId(), match.getPlayers(), match.getNextPlayer().getLogin());
					
					MatchStartedEventArgs gameArgs = new MatchStartedEventArgs(gameMessage);
					
					this.controller.fireMatchStartedEvent(gameArgs);
				}
			}
		}
	}
}
